package com.example.wangchencan

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.MenuItem
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream

class wangchencan2022110545 : AppCompatActivity() {

    private lateinit var editTextMin: EditText
    private lateinit var editTextMax: EditText
    private lateinit var textViewResult: TextView
    private lateinit var buttonStart: Button
    private lateinit var buttonStop: Button
    private var calculatingThread: Thread? = null
    private var isCalculating = false
    private var primeNumbers: MutableList<Int> = mutableListOf()

    private val handler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        editTextMin = findViewById(R.id.editTextMin)
        editTextMax = findViewById(R.id.editTextMax)
        textViewResult = findViewById(R.id.textViewResult)
        buttonStart = findViewById(R.id.buttonStart)
        buttonStop = findViewById(R.id.buttonStop)

        // 开始计算按钮点击事件
        buttonStart.setOnClickListener {
            val min = editTextMin.text.toString().toIntOrNull()
            val max = editTextMax.text.toString().toIntOrNull()

            if (min != null && max != null && min <= max) {
                primeNumbers.clear()  // 清空之前的计算结果
                startCalculation(min, max)
            } else {
                Toast.makeText(this, "请输入有效的数字区间", Toast.LENGTH_SHORT).show()
            }
        }

        // 停止计算按钮点击事件
        buttonStop.setOnClickListener {
            stopCalculation()
        }
    }

    private fun startCalculation(min: Int, max: Int) {
        isCalculating = true
        buttonStart.visibility = Button.GONE
        buttonStop.visibility = Button.VISIBLE

        calculatingThread = Thread {
            for (i in min..max) {
                if (!isCalculating) break

                if (isPrime(i)) {
                    primeNumbers.add(i)
                    handler.post {
                        textViewResult.text = primeNumbers.joinToString(", ")
                    }
                }
            }

            // 保存计算结果
            savePrimeNumbers(primeNumbers)

            handler.post {
                Toast.makeText(this, "计算完成", Toast.LENGTH_SHORT).show()
                buttonStart.visibility = Button.VISIBLE
                buttonStop.visibility = Button.GONE
            }
        }
        calculatingThread?.start()
    }

    private fun stopCalculation() {
        isCalculating = false
        calculatingThread?.interrupt()
        buttonStart.visibility = Button.VISIBLE
        buttonStop.visibility = Button.GONE
    }

    private fun isPrime(number: Int): Boolean {
        if (number < 2) return false
        for (i in 2..Math.sqrt(number.toDouble()).toInt()) {
            if (number % i == 0) return false
        }
        return true
    }

    private fun savePrimeNumbers(primes: List<Int>) {
        val file = File(filesDir, "prime_numbers.dat")
        try {
            val outputStream = ObjectOutputStream(FileOutputStream(file))
            outputStream.writeObject(primes)
            outputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    private fun loadPrimeNumbers(): List<Int> {
        val file = File(filesDir, "prime_numbers.dat")
        if (file.exists()) {
            try {
                val inputStream = ObjectInputStream(file.inputStream())
                val primes = inputStream.readObject() as List<Int>
                inputStream.close()
                return primes
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return emptyList()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.menu_history) {
            val intent = Intent(this, HistoryActivity::class.java)
            intent.putExtra("prime_numbers", ArrayList(loadPrimeNumbers()))
            startActivity(intent)
        }
        return super.onOptionsItemSelected(item)
    }
}
